package com.sunnyatwal.kettlebell;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sunnyatwal.kettlebell.clock.ClockService;
import com.sunnyatwal.kettlebell.clock.display.ClockDisplay;
import com.sunnyatwal.kettlebell.model.Exercise;

public class ClockActivity extends Activity {
	
	private static final String TAG = "ClockActivity";
	
	private static final String INTENT_FILTER_CLOCK = "com.sunnyatwal.kettlebell.clock";
	private final static String INTENT_NAME_EXERCISE = "exercise";
	
	
	private BroadcastReceiver mReceiver;
	
	private ClockDisplay mClockDisplay;
	
	private ClockService mBoundService;
	
	private Exercise mExercise;
	
	boolean mIsBound = false;
	
	
	/**
	 * Service connection to ClockService
	 */
	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mBoundService = ((ClockService.LocalBinder) service).getService();
		}

		public void onServiceDisconnected(ComponentName className) {
			mBoundService = null;
		}
	};

	
	private void destroyService() {
		Log.i(TAG, "destroyService");
		
		unbindService();
		Intent service = new Intent(ClockActivity.this, ClockService.class);
		getBaseContext().stopService(service);
	}
	
	
	private void bindService() {
		Log.i(TAG, "bindService");
		mIsBound = getApplicationContext().bindService(new Intent(ClockActivity.this, ClockService.class),
				mConnection, Context.BIND_AUTO_CREATE);
	}

	
	private void unbindService() {
		Log.i(TAG, "unbindService");
		if (mIsBound) {
			getApplicationContext().unbindService(mConnection);
			mIsBound = false;
		}
	}
	
	
	@Override 
	protected void onStart() {
		Log.i(TAG, "onStart");
		super.onStart();
	}
	
	
	@Override
	protected void onStop() {
    	Log.i(TAG, "onStop");
    	super.onStop();
    }
	
	
	@Override
	protected void onRestart() {
		Log.i(TAG, "onRestart");
		super.onRestart();
	}
	
	
	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		
		super.onResume();

		IntentFilter intentFilter = 
				new IntentFilter(INTENT_FILTER_CLOCK);
		
		mReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				
				if (intent.hasExtra(INTENT_NAME_EXERCISE)) {
					Exercise e = intent.getExtras().getParcelable(INTENT_NAME_EXERCISE);
					
					if (e.isFinished()) {
						mClockDisplay.Done();
					}
					else {
						mClockDisplay.ToDisplay(e);
					}
				}				
			}
		};
		
		this.registerReceiver(mReceiver, intentFilter);
	}
	
	
	@Override
	protected void onDestroy() {
		Log.i(TAG, "onDestroy");
		
		super.onDestroy();
		
		unbindService();
		
		Intent service = new Intent(ClockActivity.this, ClockService.class);
		getBaseContext().stopService(service);
	}
	
	
	@Override
    public void onBackPressed() {
    	Log.i(TAG, "onBackPressed");
		
    	if (mIsBound && !mBoundService.isFinished()) {
    		createExitAlert();
    	}
    	else {
    		finish();
    	}
    }
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate");
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_clock);

		getActionBar().hide();
		
		if (getIntent().hasExtra(INTENT_NAME_EXERCISE)) {
			mExercise = getIntent().getParcelableExtra(INTENT_NAME_EXERCISE);
			createFields(mExercise);
		}
				
		if (mExercise == null) {
			Log.i(TAG, "Couldn't find workout");
			throw new RuntimeException();
		}
		
		mClockDisplay.Reset();
	}
	
	
	@Override
	protected void onPause() {
		Log.i(TAG, "onPause");
		
		super.onPause();
		this.unregisterReceiver(this.mReceiver);
	}
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		Log.i(TAG, "onConfigurationChanged");
		
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.activity_clock);
		createFields(mExercise);		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.i(TAG, "onCreateOptionsMenu");
		
		getMenuInflater().inflate(R.menu.activity_clock, menu);
		return true;
	}
	
	
	public void createFields(Exercise exercise) {
		Log.i(TAG, "createFields");
				
		TextView tvWorkout = (TextView) findViewById(R.id.clock_workout);
		TextView tvExercise = (TextView) findViewById(R.id.clock_exercise);
		TextView tvWeight = (TextView) findViewById(R.id.clock_weight);
		TextView tvReps = (TextView) findViewById(R.id.clock_reps);
		ProgressBar pbRepBar = (ProgressBar) findViewById(R.id.clock_repBar);
		TextView tvRemainingTime = (TextView) findViewById(R.id.clock_remaining_time);
		TextView tvCurrentTime = (TextView) findViewById(R.id.clock_current_time);
		
		if (mClockDisplay == null) {
			mClockDisplay = new ClockDisplay(this, tvWorkout, tvExercise, tvWeight, tvReps, pbRepBar, tvRemainingTime, tvCurrentTime);			
		}
		else {
			mClockDisplay.UpdateClockFields(tvWorkout, tvExercise, tvWeight, tvReps, pbRepBar, tvRemainingTime, tvCurrentTime);
		}
	}
	
	
	public void intentPlayPause(View v) {
		Log.i(TAG, "intentPlayPause");

		if (!mIsBound) {
			Intent service = new Intent(ClockActivity.this, ClockService.class);
			service.putExtra(INTENT_NAME_EXERCISE, mExercise);
			getApplicationContext().stopService(service);
			getApplicationContext().startService(service);
			bindService();
		} else if (mBoundService.isFinished()) {
			destroyService();
    		mClockDisplay.Reset();
			intentPlayPause(v);
		} else {
			mBoundService.PauseClock();
		}
	}
	
	
	public void intentReset(View v) {
		Log.i(TAG, "intentReset");
		
		if (mIsBound && !mBoundService.isFinished()) {
			
			AlertDialog alertbox = new AlertDialog.Builder(this)
				.setMessage(getString(R.string.string_reset_workout))
		    	
		    	.setPositiveButton(getString(R.string.string_yes), 
		    			new DialogInterface.OnClickListener() {
		    	
		    				public void onClick(DialogInterface arg0, int arg1) {
		    					destroyService();
		    					mClockDisplay.Reset();
		    				}
		    				})
		    	
		    	.setNegativeButton(getString(R.string.string_no), 
		    			new DialogInterface.OnClickListener() {		    		
		    				public void onClick(DialogInterface arg0, int arg1) {}
		    				})
				.show();
			
			// Must call show() prior to fetching text view and centering
		    TextView messageView = (TextView)alertbox.findViewById(android.R.id.message);
		    messageView.setGravity(Gravity.CENTER);
		}
		else {
			destroyService();
    		mClockDisplay.Reset();
		}	
	}

	
	private void createExitAlert() {
		Log.i(TAG, "createExitAlert");
		
		AlertDialog alertbox = new AlertDialog.Builder(this)
	    	.setMessage(getString(R.string.string_quit_workout))
	    	
	    	.setPositiveButton(getString(R.string.string_yes), 
	    			new DialogInterface.OnClickListener() {
	        
	    				public void onClick(DialogInterface arg0, int arg1) {
	    					destroyService();
	    					finish();
	    				}
	    				})
	    				
			.setNegativeButton(getString(R.string.string_no), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface arg0, int arg1) {}
					})
		.show();
	    
		// Must call show() prior to fetching text view and centering
		TextView messageView = (TextView)alertbox.findViewById(android.R.id.message);
		messageView.setGravity(Gravity.CENTER);
	}
	

}
